/**
 *发送GET异步请求
 * @param {String} url
 * @param {String} params
 * @param {Function} callback
 * @param {Object} headerFn
 * @param {string} [dataType='json']
 */
function get(url, params, callback, headerFn, dataType = 'json') {
  const xhr = new XMLHttpRequest
  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
      if (xhr.status === 200) {
        let res = xhr.responseText
        switch (dataType) {
          case 'json':
            res = JSON.parse(xhr.responseText)
            break;
          default:
            break;
        }
        callback(res)
      } else {
        console.log('接口写错了', xhr.status);

      }
    }
  }
  xhr.open('get', `${url}?${params}`)
  //if (headerFn) headerFn(xhr)
  for (let key in headerFn) {
    xhr.setRequestHeader(key, headerFn[key])
  }
  xhr.send(null)
}
/**
 *发送POST异步请求
 * @param {String} url
 * @param {String} params
 * @param {Function} callback
 * @param {Object} headerFn
 * @param {string} [dataType='json']
 */
function post(url, params, callback, headerFn, dataType = 'json') {
  const xhr = new XMLHttpRequest
  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
      if (xhr.status === 200) {
        let res = xhr.responseText
        switch (dataType) {
          case 'json':
            res = JSON.parse(xhr.responseText)
            break;
          default:
            break;
        }
        callback(res)
      } else {
        console.log('接口写错了', xhr.status);

      }
    }
  }
  xhr.open('post', url)
  xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')

  for (let key in headerFn) {
    xhr.setRequestHeader(key, headerFn[key])
  }
  xhr.send(params)
}

